/*
 * Created by George on 2014/8/27.
 * APP name: mahoo 入口程序
 *
 * 采用严格 Javascript 方法
 *
 */
'use strict';


/* 模块定义
 * 注明每个模块含义
 */

// Koa 框架
var koa = require('koa');
// HTTP 服务模块
var http = require('http');
// session 管理模块
var session = require('koa-generic-session');
// redis 存储模块
var redisStore = require('koa-redis');
// var path = require('path');
// http的静态文件模块
var staticCache = require('koa-static-cache');
// favicon.ico 模块
var favicon = require('koa-favicon');
// body 模块
//var bodyParser = require('koa-bodyparser');
var bodyParser = require('koa-better-body');

var jsonp = require('koa-safe-jsonp');

//var jsonp = require('koa-safe-jsonp');
// callback 的转换程序
var thunk = require('thunkify');
var hbs = require('koa-hbs');
var Scanner = require('koa-router-scan');
//var router = require('koa-router');
//var APIroute = require('./routes/api');
//var WEBroute = require('./routes/web');

var C = require('./../config/index');

// 实例化 Koa
var app = koa();

// 设置 favicon.ico 模块
app.use(favicon());

app.use(bodyParser());

// Session 名
app.keys = ['keys', 'keykeys'];
app.use(session({
    // 默认采用 memory 方式
    store: new redisStore(),
    key: C.session.key,
    prefix: C.session.prefix,
    ttl: C.session.ttl * 1000,
    cookie: {
        domain: C.cookie.domain,
        maxage: C.cookie.maxage
    }
//    defer: true
}));

// 设置 HTTP 服务器的缓存时间
//app.use(staticCache(path.join(__dirname, 'public'), {
app.use(staticCache('./public'), {
    // 默认静态文件 cache 7 天
    maxAge: 7 * 24 * 60 * 60
});

app.use(hbs.middleware({
    viewPath: __dirname + '/views', // madatory field
    partialsPath: __dirname + '/views/partials', // 定义了partialsPath后，当模板中出现{{>partialTemplateName }}会自动插入partial
    defaultLayout: 'layout' // 所有模板的模板...其他模板会插入到{{body}}中
}));

// 注入 router 模块
//app.use(require('koa-trie-router')(app));
var scanner = new Scanner(app);
scanner.scan('../routes');


//app.use(router(APIroute));
//app.use(router(WEBroute));

jsonp(app, {
    callback: '_callback', // default is 'callback'
    limit: 50 // max callback name string length, default is 512
});


app.on('error', function (err, ctx) {
    //log.error('server error', err, ctx);
});

//var app = module.exports = http.createServer(app.callback());
//app.listen(8080);

//app = http.createServer(app.callback());
//
//if (!module.parent) {
//  app.listen(C.webPort);
//}

module.exports = app;
